package org.black.phoneUtility.app.fragment;

import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;

import org.black.phoneUtility.PhoneUtilityConstant;
import org.black.phoneUtility.R;
import org.black.phoneUtility.widget.FileAdapter;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

public class BackupFileExploreFragment extends Fragment {
	public static final String TAG = BackupFileExploreFragment.class.getName();
	private static final String LOG_TAG = BackupFileExploreFragment.class
			.getName();

	public static final String RESULT_CURRENT_FILE_PATH = "result_current_file_path";

	public static final String ARGUMENTS_FILE_PATH = "arguments_file_path";

	private ListView fileListView = null;
	private File currentFile = null;
	private FileAdapter fileAdapter;

	private class LoadFilesAsyncTask extends AsyncTask<Void, Void, File[]> {

		@Override
		protected File[] doInBackground(Void... params) {
			if (currentFile != null) {
				File[] files = currentFile.listFiles(new FileFilter() {

					@Override
					public boolean accept(File file) {
						if (file.isDirectory()) {
							return true;
						}
						return false;
					}
				});
				if (files != null) {
					Arrays.sort(files);
				}
				return files;
			}
			return null;
		}

		@Override
		protected void onPostExecute(File[] result) {
			super.onPostExecute(result);
			View view = getView();
			if (view != null) {
				TextView filePathTextView = (TextView) view
						.findViewById(R.id.backupFileExplorerFilePathTextView);
				filePathTextView.setText(currentFile.getAbsolutePath());
				if (result != null) {
					fileAdapter.addAll(result);
				}
				view.findViewById(
						R.id.backupfileExplorerLoadingPanelLinearLayout)
						.setVisibility(View.GONE);
				view.findViewById(R.id.fileExplorerListView).setVisibility(
						View.VISIBLE);
			}
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			View view = getView();
			view.findViewById(R.id.backupfileExplorerLoadingPanelLinearLayout)
					.setVisibility(View.VISIBLE);
			view.findViewById(R.id.fileExplorerListView).setVisibility(
					View.GONE);
		}

	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		new LoadFilesAsyncTask().execute();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View result = inflater.inflate(R.layout.backup_file_explorer_list,
				container, false);
		Bundle bundle = getArguments();
		String filePath = bundle.getString(ARGUMENTS_FILE_PATH);
		if (TextUtils.isEmpty(filePath) == true) {
			currentFile = Environment
					.getExternalStoragePublicDirectory(PhoneUtilityConstant.ROOT_FOLDER_NAME);
			currentFile.mkdir();
		} else {
			currentFile = new File(filePath);
		}
		if (currentFile.isDirectory() == false) {
			currentFile = currentFile.getParentFile();
		}
		Log.i(LOG_TAG, "currentFile: " + currentFile.getAbsolutePath());
		this.fileAdapter = new FileAdapter(getActivity(),
				R.layout.file_explorer_row);

		ImageButton perviousItemButton = (ImageButton) result
				.findViewById(R.id.backupFileExplorerPerviousItemButton);
		perviousItemButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				FragmentManager fragmentManager = getActivity()
						.getFragmentManager();
				Fragment fragment = new BackupFileExploreFragment();

				Bundle bundle = new Bundle();
				String path = null;
				if (currentFile.getParentFile() != null) {
					path = currentFile.getParentFile().getAbsolutePath();
				} else {
					path = currentFile.getAbsolutePath();
				}
				bundle.putString(ARGUMENTS_FILE_PATH, path);
				fragment.setArguments(bundle);

				fragmentManager
						.beginTransaction()
						.replace(
								R.id.phone_utility_backup_file_explorer_main_content_frame,
								fragment, BackupFileExploreFragment.TAG)
						.commit();

			}
		});
		this.fileListView = (ListView) result
				.findViewById(R.id.fileExplorerListView);
		this.fileListView.setAdapter(fileAdapter);
		this.fileListView
				.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						File file = (File) parent.getItemAtPosition(position);
						if (file.isDirectory() == true) {
							FragmentManager fragmentManager = getActivity()
									.getFragmentManager();
							Fragment fragment = new BackupFileExploreFragment();

							Bundle bundle = new Bundle();
							String path = file.getAbsolutePath();
							bundle.putString(ARGUMENTS_FILE_PATH, path);
							fragment.setArguments(bundle);

							fragmentManager
									.beginTransaction()
									.replace(
											R.id.phone_utility_backup_file_explorer_main_content_frame,
											fragment,
											BackupFileExploreFragment.TAG)
									.commit();
						} else {

						}
					}
				});
		Button backupFileExplorerOkButton = (Button) result
				.findViewById(R.id.backupFileExplorerOkButton);
		backupFileExplorerOkButton
				.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						Intent returnIntent = new Intent();
						returnIntent.putExtra(RESULT_CURRENT_FILE_PATH,
								currentFile.getAbsolutePath());

						getActivity().setResult(Activity.RESULT_OK,
								returnIntent);
						getActivity().onBackPressed();
					}
				});

		return result;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		this.currentFile = null;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			getActivity().onBackPressed();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

}
